//
//  MainTableViewController.m
//  Contacts
//
//  Created by 李 雷川 on 14-7-15.
//  Copyright (c) 2014年 李 雷川. All rights reserved.
//

#import "MainViewController.h"
#import "LatestNoticeCell.h"
#import "TopBannerView.h"
#import "FunctionView.h"
#import "NoticeViewController.h"
#import "CompanyView.h"
#import "UserCenterViewController.h"
#import "ActivityViewController.h"
#import "ServerInterface.h"
#import "Contact.h"
#import "LatestNotice.h"
#import "Company.h"
#import "NoticeHeaderView.h"
#import "NoticeDetailViewController.h"
#import "FileInterface.h"
#import "ImageExt.h"
#import "NoticeCategory.h"
#import "Notice.h"
#import "ContactViewController.h"
#import "MJRefresh.h"

extern Contact *globalContact;
@interface MainViewController () <UITableViewDataSource,UITableViewDelegate>{
    NSArray  *functions;
    IBOutlet UITableView *mainTableView;
    IBOutlet UILabel     *companyLabel;
    UIButton   *headButton;
    NSArray  *notices;
}
@property(nonatomic, strong)  NSArray  *functionArr;
@property(nonatomic, strong)  NSArray  *news;
@property(nonatomic, strong)  UITableView *mainTableView;
@end

@implementation MainViewController
@synthesize functionArr,news,mainTableView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    

    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }

    //初始化一个UIButton
    headButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置UIButton.bounds的位置大小
    headButton.bounds = CGRectMake( 0, 0, 40,40);

    [headButton addTarget:self action:@selector(enterUserCenterViewController) forControlEvents:UIControlEventTouchUpInside];
    [headButton setClipsToBounds:YES];
    [headButton.layer setBorderColor:[UIColor colorWithRed:255 green:255 blue:255 alpha:0.7].CGColor];
    [headButton.layer setBorderWidth:1.0];
    [headButton.layer setCornerRadius:headButton.bounds.size.width/2.0];
    //通过initWithCustomView：方法把UIButton加导UIBarButtonItem中
    UIBarButtonItem *sureButtonItem = [[UIBarButtonItem alloc] initWithCustomView:headButton];
    
    self.navigationItem.rightBarButtonItem = sureButtonItem;
    
    companyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 20,100, 44)];
      companyLabel.text = globalContact.company.name;
    companyLabel.textColor = [UIColor whiteColor];
    companyLabel.font = [UIFont systemFontOfSize:14];
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:companyLabel];
    [companyLabel sizeToFit];
    self.navigationItem.leftBarButtonItem = leftButtonItem;


    
    
    mainTableView.separatorColor = [UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1];
    
    Funtion *funtion1 = [[Funtion alloc]init];
    funtion1.type = 0;
    funtion1.name = @"通知";
    
    Funtion *funtion2 = [[Funtion alloc]init];
    funtion2.type = 1;
    funtion2.name = @"通讯录";
    
    Funtion *funtion3 = [[Funtion alloc]init];
    funtion3.type = 2;
    funtion3.name = @"敬请期待";
    
    self.functionArr = @[funtion1,funtion2,funtion3];
    [self initLastestNotices];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateFirstIndexNews) name:k_NewMessage object:nil];

    __weak MainViewController * controller = self;
    [mainTableView addHeaderWithCallback:^{
        [controller updateFirstIndexNews];
    }];
    mainTableView.headerPullToRefreshText = @"下拉可以刷新了";
    mainTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    mainTableView.headerRefreshingText = @"正在更新最新消息";
    [mainTableView headerBeginRefreshing];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{

    UIImage *headImage = [UIImage imageNamed:@"logo.png"];
    NSString *fullImagePath = [IMAGE_FORDER stringByAppendingPathComponent:globalContact.headName];
    if ([[NSFileManager defaultManager]fileExistsAtPath:fullImagePath]) {
        headImage =[UIImage imageWithContentsOfFile:fullImagePath];
        [headButton setImage:headImage forState:UIControlStateNormal];
    }
    else{
        //设置UIButton的背景图片
        [headButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:globalContact.headUrl] placeholderImage:
         [UIImage imageNamed:@"logo.png"]];
    }


    [mainTableView reloadData];

}
-(void)viewDidAppear:(BOOL)animated{
    self.navigationItem.titleView.hidden = YES;
}

-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:k_NewMessage object:nil];
}

-(void)updateFirstIndexNews{
    NSDictionary *paramDic = @{@"company_id":CompanyID,@"token":globalContact.token,@"user_id":@(globalContact.userID)};
    [ServerInterface getCategoryWithDic:paramDic withBlock:^(NSDictionary *newDic, NSError *error) {
        //NSLog(@"news is:%@",newDic);
       
        if (error) {
            //NSLog(@"error is:%@",error);
        }
        else{
            if ([[newDic valueForKeyPath:@"success"] boolValue]) {
                NSArray *newArr = newDic[@"data"];
                NSMutableArray *arr = [NSMutableArray arrayWithCapacity:newArr.count];
                for (NSDictionary *categoryDic in newArr) {
                    NoticeCategory *category = [NoticeCategory analysisNoticeCategoryWithDic:categoryDic];
                    [arr addObject:category];
                }
                NSArray  *categorys = [NSArray arrayWithArray:arr];
                [NoticeCategory saveWithCategorys:categorys];
                NSDictionary *indexNewsDic = @{@"company_id":CompanyID,@"token":globalContact.token,@"user_id":@(globalContact.userID)};
                [ServerInterface getFirstIndexNewsWithDic:indexNewsDic withBlock:^(NSDictionary *newDic, NSError *error) {
                    //NSLog(@"news is:%@",newDic);
                    if (error) {
                       // NSLog(@"error is:%@",error);
                    }
                    else{
                        if ([[newDic valueForKeyPath:@"success"] boolValue]) {
                            NSArray *newArr = newDic[@"data"];
                            [FileInterface saveLatestNoticesWithNotices:newArr];
                            [self analsyisNotices:newArr];
                            [mainTableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
                            
                        }
                        else{
                        }
                    }
                   
                }];
                
            }
            else{
                
            }
        }
        [self.mainTableView headerEndRefreshing];
    }];
}

-(void)analsyisNotices:(NSArray *)_notices{
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:_notices.count];
    for (NSDictionary *noticeDic in _notices) {
        LatestNotice *notice = [LatestNotice analysisLatestNoticeWithDic:noticeDic];
        NoticeCategory *category  = [NoticeCategory getCategoryWithID:notice.categoryID];
        notice.iconUrl = category.ico;
        [arr addObject:notice];
    }
    notices = [NSArray arrayWithArray:arr];
}
-(void)initLastestNotices{
    NSArray *_notices = [FileInterface getLatestNotices];
    [self analsyisNotices:_notices];
}

-(void)enterUserCenterViewController{
    UserCenterViewController *userCenterViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"UserCenterViewController"];
    [self.navigationController pushViewController:userCenterViewController animated:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    float rowHeight;
    switch (indexPath.section) {
        case 0:
            rowHeight = 110;
            break;
        case 1:
            rowHeight = 74;
            break;
        default:
            break;
    }
    return rowHeight;
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 1:
            return @"最新消息";
            break;
        default:
            break;
    }
    return nil;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    NSInteger row = 0;
    switch (section) {
        case 0:
            row = 1;
            break;
        case 1:
            row = notices.count;
            break;
        default:
            break;
    }
    return row;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 0:{
            return 0;
        }
            break;
        case 1:{
            return 20;
        }
            break;
            
        default:
            break;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    switch (section) {
//        case 0:{
//            CompanyView *companyView = [[CompanyView alloc]initWithFrame:CGRectMake(0, 0,CGRectGetWidth(mainTableView.frame), 44)];
//            companyView.section = section;
//            companyView.tableView = tableView;
//            return companyView;
//        }
//            break;
//        case 1:{
//            NoticeHeaderView *view = [[NoticeHeaderView alloc]initWithFrame:CGRectMake(0, 0,CGRectGetWidth(mainTableView.frame),24)];
//            view.section = section;
//            view.tableView = tableView;
//            return view;
//        }
//            break;
//            
//        default:
//            break;
//    }
    return nil;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    switch (indexPath.section) {
        case 0:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"functionCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"functionCell"];
               
            }
            float width = 84;
            float height = 110;
            float space = (CGRectGetWidth(mainTableView.frame) - width *3)/4;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            for (NSInteger i = 0; i < 3; i++) {
                CGRect frame = CGRectMake(space + (width +space) * i,0,width,height);
                FunctionView *functionView = [[FunctionView alloc]initWithFrame:frame];
                [functionView initWithFuntion:[functionArr objectAtIndex:i]];
                [cell addSubview:functionView];
                functionView.functionBtn.tag = i;
                functionView.enterBlock=^(){
                    [self enterFunctionController:i];
                };
            }
        }
            break;
        case 1:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"LatestNoticeCell" forIndexPath:indexPath];
            LatestNoticeCell *noticeCell = (LatestNoticeCell *)cell;
            [noticeCell initWithLatestNotice:notices[indexPath.row]];
        }
            break;
        default:
            break;
    }
    cell.backgroundColor =[UIColor whiteColor];
    // Configure the cell...
    return cell;
}




-(void)enterFunctionController:(NSInteger)funtionType{
    switch (funtionType) {
        case 0:{
            NoticeViewController *noticeViewController = [self.storyboard  instantiateViewControllerWithIdentifier:@"NoticeViewController"];
            [self.navigationController pushViewController:noticeViewController animated:YES];
        }
            break;
        case 1:{
            ContactViewController *controller = [self.storyboard  instantiateViewControllerWithIdentifier:@"ContactViewController"];
            [self.navigationController pushViewController:controller animated:YES];
        }
            break;
        case 2:{
            return;
            ActivityViewController *activityViewController = [self.storyboard  instantiateViewControllerWithIdentifier:@"ActivityViewController"];
            [self.navigationController pushViewController:activityViewController animated:YES];
        }
            break;
            
        default:
            break;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
     NSIndexPath *selected = [mainTableView indexPathForSelectedRow];
     [mainTableView deselectRowAtIndexPath:selected animated:YES];
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.destinationViewController isKindOfClass:[NoticeDetailViewController class]]) {
        NoticeDetailViewController *detailView = segue.destinationViewController;
        LatestNotice *latestNotice = notices[selected.row];
        Notice *notice = [Notice getNoticeWithID:latestNotice.objID];
        if (!notice) {
            notice = [[Notice alloc]init];
            notice.ID = latestNotice.objID;
            notice.title = latestNotice.title;
            [Notice saveWithNotice:notice];
        }
        [detailView initNotice:notice];
        detailView.finishLoadBlock = ^(){
            [mainTableView reloadRowsAtIndexPaths:@[selected] withRowAnimation:UITableViewRowAnimationNone];
        };
    }

}


@end
